package com.businessportal.web.controllers.blog;

import com.businessportal.web.dataaccess.entities.BlogEntity;
import com.businessportal.web.dataaccess.entities.Login;
import com.businessportal.web.dataaccess.services.UserService;
import org.json.simple.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * Created by Vadim on 6/28/14.
 */
@WebServlet(urlPatterns = "/securepages/blog_deleter.do")
public class BlogDeleterController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");

        JSONObject retVal=new JSONObject();

        try {

            String blogId = req.getParameter("blogId");

            if(null!= blogId && !blogId.isEmpty()){

                HttpSession session = req.getSession();
                Login user = (Login)session.getAttribute("user");

                for(BlogEntity item : user.getBlogs()){
                    if(item.getId() == Long.parseLong(blogId)){
                        user.getBlogs().remove(item);
                        break;
                    }
                }

                UserService.INSTANCE.UpdateUser(user);

                retVal.put("message", "OK");
            } else {
                retVal.put("message", "Not found");
            }

        }catch (Exception e){
            retVal.put("error", e.getMessage());
        }

        resp.getWriter().write(retVal.toString());
    }
}
